package com.tcs.reptile.proxyip;

import java.io.IOException;
import java.util.List;

import javax.annotation.Resource;

import org.apache.commons.lang.StringUtils;
import org.jsoup.Jsoup;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.stereotype.Component;

import com.fasterxml.jackson.databind.ObjectMapper;
import com.tcs.model.IpBean;
import com.tcs.server.dist.IDistService;
import com.tcs.util.constant.SystemConstants;

@Component("proxyIpServiceImpl")
public class ProxyIpServiceImpl implements ProxyIpService {
	
	private final Logger logger = LoggerFactory.getLogger(ProxyIpServiceImpl.class);
	
	@Resource(name="distServiceImpl")
	private IDistService iDistService;
	
	@Override
	public IpBean getMyProxyPoll() {
		// 预留
		return null;
	}

	@Override
	public List<IpBean> getMyProxyPollList(Integer size) {
		// 预留
		return null;
	}
	
	private String getChargeIp(Integer count) {
		if (StringUtils.isBlank(SystemConstants.ReptileConstants.APPKEY)) {
			SystemConstants.ReptileConstants.APPKEY = iDistService.getValueByKey(SystemConstants.ReptileConstants.MOGU);
		}
		StringBuilder ipSb = new StringBuilder();
		ipSb.append("http://piping.mogumiao.com/proxy/api/get_ip_al?appKey").append(SystemConstants.ReptileConstants.APPKEY)
		.append("&count=").append(count)
		.append("&expiryDate=0&format=1&newLine=2");
		return ipSb.toString();
	}

	@Override
	public IpBean getChargeVPSProxyIp() {
		IpBean ipBean = null;
		try {
			String src = Jsoup.connect(getChargeIp(1)).get().text();
			ObjectMapper mapper = new ObjectMapper();
			mapper.readValue(src, IpBean.class);
		} catch (IOException e) {
			logger.error("" , e);
		}
		return ipBean;
	}

	@SuppressWarnings("unchecked")
	@Override
	public List<IpBean> getChargeVPSProxyIpList(Integer size) {
		List<IpBean> ipResultList = null;
		try {
			String src = Jsoup.connect(getChargeIp(size)).get().text();
			ObjectMapper mapper = new ObjectMapper();
			ipResultList = mapper.readValue(src, List.class);
		} catch (IOException e) {
			logger.error("" , e);
		}
		return ipResultList;
	}
}